<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use App\Utils\FileUploader;
use App\Models\CourseClass;
use App\Models\CourseClassAbout;
use App\Models\WechatNews;
use App\Models\Tags;
use App\Contant\TagsType;
use App\Models\Ctype;
use App\Models\WechatSubscribePush  as SubscribePush;
use App\Models\WechatMenu;
use App\Models\WechatKeywordSet;
use App\Utils\WxQRcode;

class WechatController extends Controller
{

    //获得全局access_token
    public function getToken(){
        $appId = "wx4001963936e98f4f";   //appid
        $appSecret = "6cd114f956d35b5af8655c889c0d8303";
        if(Redis::exists('access_token') && Redis::get('access_token') != ''){
            $access_token = Redis::get('access_token');
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
            $data = $this->curl($url);
            $tokenInfo = json_decode($data,true);
            $access_token = $tokenInfo['access_token'];
            Redis::setex('access_token',7200,$access_token);
        }
        return $access_token;
    }

    public function curl($url,$postData = '',$type = ''){
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$url); //要访问的地址
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证

        if($postData){
            curl_setopt($ch, CURLOPT_POST, 1);//post方法请求
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);//post请求发送的数据包
        }else{
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        }

        $data = curl_exec($ch);
        if(curl_errno($ch)){
            logger()->info(curl_error($ch));
        }
        curl_close($ch);
        return $data;
    }

/**
 * 测试
 *
 */
public function testGetAccessToken(){
    $appid = "wx550f84c4ffa15d13";
    $appsecret = "d4624c36b6795d1d99dcf0547af5443d";
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx550f84c4ffa15d13&secret=d4624c36b6795d1d99dcf0547af5443d";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    $jsoninfo = json_decode($output, true);
    $access_token = $jsoninfo["access_token"];
    return $access_token;
}
    //设置自定义菜单

    public function setMenu($button){
    	$button = $button;
        $access_token = $this->getToken();
        //$access_token = $this->testGetAccessToken();//测试

    	$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $button);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Errno'.curl_error($ch);
        }
        curl_close($ch);
        return $tmpInfo;
    }

    //20180905 课程素材管理
    public function courselist(Request $request){
        $title = $request->input('title','');
        $courseClass = new CourseClass();
        if($title){
            $courseClass = $courseClass->where('title','like',"%{$title}%");
        }
        $courseClass = $courseClass->orderBy('id','desc')->paginate(15);
        $data['courseClass'] = $courseClass;
        $data['title'] = $title;
        return view('wechat.index',$data);
    }

    //20180905  添加素材
    public function addImg(Request $request){
        $class_id = $request->input('id');
        $courseClass = CourseClass::where('id',$class_id)->select("id", "title")->first();
        $about       = CourseClassAbout::where("course_class_id", $class_id)->select("id", "activity_url","wx_keyword")->first();

        $data['item']= $courseClass;
        $data['about'] = $about;
        return view("wechat.add", $data);
    }

    //20180905  执行编辑
    public function updateImg(Request $request){
        $data = $request->input();
        if($request->input("id")){
            $about = CourseClassAbout::where("id", $request->input("id"))->first();
            $about->activity_url = $request->input("activity_url");
            $about->activity_two_url = $request->input("activity_two_url");
            $about->wx_keyword   = $request->input("wx_keyword");
            $about->remark       = $request->input("remark");
        }else{
            $about = new CourseClassAbout();
            $about->activity_url     = $request->input("activity_url");
            $about->activity_two_url = $request->input("activity_two_url");
            $about->course_class_id  = $request->input("course_class_id");
            $about->wx_keyword       = $request->input("wx_keyword");
            $about->remark = $request->input("remark");
        }
         //执行保存
        if($about->save()){
            return redirect('/wechat/list');
        }else{
            $this->getSessionInfo($request,'error');
            return false;
        }  

    }


    //20180904  上传图片
    public function uplodeTmp(Request $request){
        // $upload  = new FileUploader();
        // $img     = $_FILES["image"];
        // $result  = $upload->formUpload($img, 'upload/avatar');
        // if($result['code']==1){
        //     $file_path = env('IMG_URL').$result['path'];
        //     $result['file_path'] = $file_path;
            //return json_encode($result);
        // }
       
        $file_info= array(
            'filename'=>'/upload/image/20180723/1532328602.1978295711.jpeg',  //国片相对于网站根目录的路径
            'content-type'=>'image/jpg',  //文件类型
            'filelength'=>'72'         //图文大小
        );
        $token= "13_6mEXsLZ6ZXRE4xz8lNf5tTKkorF70JRA8ILOfZ2ProxoVn8IBqYig-Ic55-NlqmZ9t6Iznvt12C5NoaeoMNsUI3oiEbJstToazGHNzzCXdcWQELRwW4zsFbvHnsZVPaAEATPJ";
        $type = "image";  //声明上传的素材类型，这里为image
        //$url  = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=".$type;//永久
        $url  = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=".$type;//临时
        $real_path= new \curlFile($_SERVER['DOCUMENT_ROOT'].$file_info['filename']);
        $data= array("media"=>$real_path, 'form-data'=>$file_info);

        $ch1 = curl_init();
        $timeout =60;
        curl_setopt ( $ch1, CURLOPT_URL, $url );
        curl_setopt ( $ch1, CURLOPT_POST, 1 );
        curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
        curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch1, CURLOPT_SAFE_UPLOAD, true);
        curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
        @curl_setopt ( $ch1, CURLOPT_POSTFIELDS, $data );
        $result = curl_exec ($ch1);
        curl_close ($ch1);
        
        return json_encode($result);
    }


    /**
     * 微信上传菜单栏
     */
    public function menu(){

        $menu = new WechatMenu();
        $data = $menu->get();
        foreach($data as $k=>$v){
            $a = json_decode($v['content'],true);
            $data[$k]['name'] = $a['name'];
        }
        $count = count($data);
        return view("wechat.menuIndex",['list'=>$data,'count'=>$count]);
    }
    /**
     * 添加菜单栏
     */
    public function menuAdd(){
        $menu = new WechatMenu();
       
        return view("wechat.menuAdd");
    }

    public function menuStore(Request $request){
        $data = $request->input();
        array_shift($data);

        $data2 = array_chunk($data, 3);
        $count = count($data2);
        if($count == 1){
            foreach($data2 as $k=>$v){
                $data3[$k]['name'] = $v[0]; 
                if($v[1] == 2){
                    $data3[$k]['type'] = "view";
                    $data3[$k]['url'] = $v[2]; 
                }elseif($v[1] == 1){
                    $data3[$k]['type'] = "click";
                    $data3[$k]['key'] = $v[2]; 
                }
            }
            $json = $data3[0];

        }else{
            foreach($data2 as $k=>$v){
                $data3[$k]['name'] = $v[0]; 
                if($v[1] == 2){
                    $data3[$k]['type'] = "view";
                    $data3[$k]['url'] = $v[2]; 
                }elseif($v[1] == 1){
                    $data3[$k]['type'] = "click";
                    $data3[$k]['key'] = $v[2]; 
                }
            }
            $json['name'] = $data3[0]['name']; 
            array_shift($data3);
            $json['sub_button'] = $data3;
        }
        
        $button = json_encode($json, JSON_UNESCAPED_UNICODE);
        $menu = new WechatMenu(); 
        $a['content'] = $button;
        $re = $menu ->menuAdd($a);
        if($re){
            return redirect("wechat/menu");
        }
}
        public function generate(){
             $menu = new WechatMenu(); 
             $data = $menu->whereNull("deleted_at")->select("content")->get()->toArray();
            
             foreach($data as $k=>$v){
                $a[$k] = json_decode($v['content'],true);
             }
             $b['button'] = $a;
             $button = json_encode($b, JSON_UNESCAPED_UNICODE);
            //dd($button);
            $str = $this->setMenu($button);
            $str1 = json_decode($str,true);
        
            if($str1['errmsg'] == 'ok'){
                echo '<script>alert("生成成功");window.location.href="/wechat/menu";</script>';
            }else{
                echo '<script>alert("生成失败");window.location.href="/wechat/menu";</script>';
            }

        }
        public function menuUpdate(Request $request){
            $id = $request->input("id");
            $menu = new WechatMenu(); 
            $data =  $menu->where("id",$id)->select("content")->get()->toArray();

            $json = json_decode($data[0]['content'],true);
            $count = count($json);
           // dd($json);
            return view("wechat.menuUpdate",['data'=>$json,'id'=>$id]);
        }
        public function dataUpdate(Request $request){
            $data = $request->input();
            $id = $data['id'];
            array_shift($data);
            array_shift($data);
            $data2 = array_chunk($data, 3);
            $count = count($data2);
        if($count == 1){
            foreach($data2 as $k=>$v){
                $data3[$k]['name'] = $v[0]; 
                if($v[1] == 2){
                    $data3[$k]['type'] = "view";
                    $data3[$k]['url'] = $v[2]; 
                }elseif($v[1] == 1){
                    $data3[$k]['type'] = "click";
                    $data3[$k]['key'] = $v[2]; 
                       }
             }
         $json = $data3[0];

          }else{
               
              foreach($data2 as $k=>$v){

                  $data3[$k]['name'] = $v[0]; 
                  if($v[1] == 2){
                      $data3[$k]['type'] = "view";
                      $data3[$k]['url'] = $v[2]; 
                  }elseif($v[1] == 1){
                      $data3[$k]['type'] = "click";
                      $data3[$k]['key'] = $v[2]; 
                  }
              }
              $json['name'] = $data3[0]['name']; 
              array_shift($data3);
              $json['sub_button'] = $data3;
          }
        $button = json_encode($json, JSON_UNESCAPED_UNICODE);
        $menu = new WechatMenu(); 
        $a['content'] = $button;
        $menu = new WechatMenu(); 
         $re = $menu->updateData($id,$a);
         if($re){
            return redirect("wechat/menu");
         }
         
    }
    public function menuDelete(Request $request){
        $id = $request->input("id");

        $menu = new WechatMenu();
        $re = $menu->where("id",$id)->delete();
        if($re){
            return redirect("wechat/menu");
         }
    }

    /**
     * 20180913
     * 微信关注后自动回复图文列表
     */ 
    public function news(Request $request){

        $title = $request->input('title','');
        $new = new WechatNews();
        if($title){
            $new = $new->where('title','like',"%{$title}%");
        }
        $new = $new->orderBy('orderby','desc')->paginate(15);
        $data['courseClass'] = $new;
        $data['title'] = $title;
        return view('wechat.news',$data);
    }
    /**
     * 20180913
     * 新增微信图文
     */
    public function addNew(){

        return view("wechat.addnew");
    }

    /**
     * 20180913
     * 编辑微信图文
     */
    public function editNew($id){
        if($id){
            $new = WechatNews::where("id", $id)->first();
        }
        $data['new'] = $new;
        return view("wechat.editnew", $data);
    }

    /*
     * 删除微信图文（整体）
     */
    public function delNew(Request $request){
        $id = $request->input('id');
        $result = WechatNews::where('id',$id)->delete();
        if($result){
            return $this->getMessage(0,'删除成功');
        }else{
            return $this->getMessage(1,'删除失败');
        }
    }

    /**
     * 20180913
     * 新增微信图文插入
     */
    public function insertNew(Request $request){
        $data = $request->input();
        if($request->input("id")){
            $new = WechatNews::where("id", $request->input("id"))->first();
            $new->title      = $request->input("title");
            $new->description= $request->input("description");
            $new->picurl     = $request->input("picurl");
            $new->url        = $request->input("url");
            $new->orderby    = $request->input("orderby");
            $new->opertion_user_id = $request->user()->id;
        }else{
            $new = new WechatNews();
            $new->title      = $request->input("title");
            $new->description= $request->input("description");
            $new->picurl     = $request->input("picurl");
            $new->url        = $request->input("url");
            $new->orderby    = $request->input("orderby");
            $new->opertion_user_id = $request->user()->id;
        }
         //执行保存
        if($new->save()){
            return redirect('/wechat/news');
        }else{
            $this->getSessionInfo($request,'error');
            return false;
        }
    }
       //media上传素材
    public function uploadMedia($img_url){
       
        $file_info= array(
            'filename'=> $img_url,//$url,  //国片相对于网站根目录的路径
            'content-type'=>'image/jpg',  //文件类型
            'filelength'=>'72'         //图文大小
        );

        //$token=  $this->getToken11();
        $token=  $this->getToken();

        $type = "image";  //声明上传的素材类型，这里为image
        //$url  = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=".$type;//永久
        $url  = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=".$type;//临时
        $real_path= new \curlFile($_SERVER['DOCUMENT_ROOT'].$file_info['filename']);

        $data= array("media"=>$real_path, 'form-data'=>$file_info);

        $ch1 = curl_init();
        $timeout =60;
        curl_setopt ( $ch1, CURLOPT_URL, $url );
        curl_setopt ( $ch1, CURLOPT_POST, 1 );
        curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
        curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch1, CURLOPT_SAFE_UPLOAD, true);
        curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
        @curl_setopt ( $ch1, CURLOPT_POSTFIELDS, $data );
        $result = curl_exec ($ch1);

        // 返回最后一次的错误号
//         $err_code = curl_errno($ch1);
//         dd($err_code);
        curl_close ($ch1);
       
        return $result;
    }

    /*
     * 创建回复
     */
    public function postKeywordSet(Request $request){

        $upload  = new FileUploader();
        $arr =  $upload->upload($request,'img_url','/upload/image');

        $img_url = $arr['url'];
        $data1 = $this->uploadMedia($img_url);

        $str = json_decode($data1,true);

        $media_id = $str['media_id'];
        $keyword = $request->input('keyword');
        $content = $request->input('content');
        $contents = explode(PHP_EOL,$content);
        $reply = '';
        for($i = 0;$i< count($contents);$i++){
            if(empty($contents[$i])){
                continue;
            }
            if($i == count($contents)-1){
                $reply .= trim($contents[$i]);
            }else{
                $reply .= trim($contents[$i])."\n";
            }
        }

        $keywordSet = new WechatKeywordSet();
        $keywordSet->keyword = $keyword;
        $keywordSet->reply_content = $reply;
       // $keywordSet->media_url = $str['url'];
        $keywordSet->media_id = $media_id;
        $keywordSet->img_url = $img_url;

        if($keywordSet->save()){
            $this->getSessionInfo($request,'success','添加成功');
            return redirect('/wechatSet/list');
        }else{
            $this->getSessionInfo($request,'fail','添加失败');
            return redirect('/wechatSet/keywordAdd');
        }
    }

      /*
     *更新关键词设置
     */
    public function updateKeywordSet(Request $request){
      
        $id = $request->input('id');
        $arr = $_FILES;
        //dd($arr);
        if(!empty($arr['img_url']['name'])){
            $upload  = new FileUploader();
            $arr1 =  $upload->upload($request,'img_url','/upload/image');

            $img_url = $arr1['url'];

            $data1 = $this->uploadMedia($img_url);

            $str = json_decode($data1,true);
            
            $media_id = $str['media_id'];
           // $media_url = $str['url'];
            
        }else{
            $img_url = $request->input('img_url1');
            $media_id = $request->input('media_id1');
           // $media_url = $request->input('media_url1');

        }
       // dd($$img_url);
        $keyword = $request->input('keyword');
        $content = $request->input('content');
        $contents = explode(PHP_EOL,$content);
        $reply = '';
        for($i = 0;$i< count($contents);$i++){
            if(empty($contents[$i])){
                continue;
            }
            if($i == count($contents)-1){
                $reply .= trim($contents[$i]);
            }else{
                $reply .= trim($contents[$i])."\n";
            }
        }
        $keywordSet = WechatKeywordSet::where('id',$id)->first();
        $keywordSet->keyword = $keyword;
        $keywordSet->reply_content = $reply;
        //$keywordSet->media_url = $media_url;
        $keywordSet->media_id = $media_id;
        $keywordSet->img_url = $img_url;
        if($keywordSet->save()){
            $this->getSessionInfo($request,'success','修改成功');
            return redirect('/wechatSet/list');
        }else{
            $this->getSessionInfo($request,'fail','修改失败');
            return redirect('/wechatSet/keywordAdd');
        }
    }

    //获得全局access_token
    public function getToken11(){
        $appId = "wx550f84c4ffa15d13";   //appid
        $appSecret = "d4624c36b6795d1d99dcf0547af5443d";
        // if(Redis::exists('access_token') && Redis::get('access_token') != ''){
        //     $access_token = Redis::get('access_token');
        // }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
            $data = $this->curl($url);
            $tokenInfo = json_decode($data,true);
            $access_token = $tokenInfo['access_token'];
        //     Redis::setex('access_token',7200,$access_token);
        // }
        return $access_token;
    }

    public function setList(Request $request){
        $subscribe = SubscribePush::get();
        return view('wechat.courseSet.list',['subscribe'=>$subscribe]);
    }

    /*
     *
     */
    public function postCourseSet(Request $request){

        return view('wechat.courseSet.create');
    }
    /*
     * 添加设置
     */
    public function postSetCreate(Request $request){
        $course_id = $request->input('courseId');
        $subscribe = new SubscribePush();
        $subscribe->course_class_id = $course_id;
        if($subscribe->save()){
            $courseClass = CourseClass::where('id',$course_id)->first();
            Redis::set('push_article',json_encode($courseClass));
            return redirect('/wechatSet/push/list');
        }
    }
    /*
     * 修改页
     */
    public function setCourseUpdate(Request $request){
        $id = $request->input('id');
        $subscribe = SubscribePush::where('id',$id)->first();
        $courseClass = json_decode(Redis::get('push_article'));
        return view('wechat.courseSet.edit',['subscribe'=>$subscribe,'courseClass'=>$courseClass]);
    }

    /*
     *
     */
    public function postCourseUpdate(Request $request){
        $id = $request->input('id');
        $subscribe = SubscribePush::where('id',$id)->first();
        $course_id = $request->input('courseId');
        $subscribe->course_class_id = $course_id;
        if($subscribe->save()){
            $courseClass = CourseClass::where('id',$course_id)->first();
            Redis::set('push_article',json_encode($courseClass));
            return redirect('/wechatSet/push/list');
        }
    }

    /*
    *20190109
    *生成带参数二维码 
    */
    public function createdQrcode(Request $request){

        $info = $request->input("info", "");
        if($info){
            $access_token = Redis::get('access_token');
            //$access_token = "17_5nSmBhKrHlsfn7MHiLFQGPrRoOItICw7bPx8O4oEt3acamqHDyG-rOWFaHEHUBSWdYf28xTSs5NVUjlt7QNctVC10rWK7K4CyYZw9lJS3x2gbTeunIFtNwL5NzkWMOeAHAEUW";
            $WxQRcode     = new WxQRcode($access_token);
            $img          = $WxQRcode->_getQRCode(2592000,"temp", $info);
            
            echo json_encode(array("code"=>1, "msg"=>"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$img));
            return;
        }

        return view('wechat.qrcode');
    }

}
